package com.xwaiy.xwaiyrpc.loadbalancer;

import com.xwaiy.xwaiyrpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡器
 * @Author Xwaiy
 * @Date 2025/9/2 13:58
 **/
public class RoundRobinLoadBalancer implements LoadBalancer{

    // 当前下标
    private final AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ServiceMetaInfo select(Map<String, Object> params, List<ServiceMetaInfo> list) {
        if(list.isEmpty()){
            return null;
        }
        int size = list.size();
        if(size==1){
            return list.get(0);
        }
        int index = currentIndex.getAndIncrement() % size;
        return list.get(index);
    }
}
